package in.miraclesirius.arunachaltimes;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class WordpressMainFragment extends Fragment {

	OnHeadlineSelectedListener mCallback;

	public final static String RELATIVE_URL = "AT.Story.URL";
	public final static String DIV_ID = "AT.Story.divId";
	public final static String PAGE_TITLE = "AT.Story.pageTitle";

	String url = "http://www.arunachaltimes.in/wordpress/"; // getResources().getString(R.string.mainUrl);

	String Newsstory;
	ProgressDialog mProgressDialog;
	View rootView;
	private StoryAdapter adapter;
	private GridView mStoryList;
	private ArrayList<StoryEntryModel> stories;

	public WordpressMainFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_home, container, false);
		mStoryList = (GridView) rootView.findViewById(R.id.homestoryList);

		Bundle pigeon = this.getArguments();
		url+= pigeon.getString(WordpressMainActivity.SECTIONA_NAME);
		new ArunachalTimesStory(getActivity()).execute();

		mStoryList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				mCallback.onArticleSelected(stories.get(position)
						.getFullstoryUrl());
			}
		});
		return rootView;
	}

	public interface OnHeadlineSelectedListener {
		public void onArticleSelected(String fullstoryUrl);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		try {
			mCallback = (OnHeadlineSelectedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnHeadlineSelectedListener");
		}
	}

	private class ArunachalTimesStory extends AsyncTask<Void, Void, Void> {

		Activity mContex;
		Elements newsBody;

		public ArunachalTimesStory(Activity contex) {
			this.mContex = contex;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(mContex);
			mProgressDialog.setMessage("Loading Arunachal times...");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.show();
			newsBody = new Elements();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Document document = Jsoup.connect(url).timeout(0).get();
				newsBody = document.select("#content-main").select(
						"[id^=post-]");

			} catch (IOException e) {
				Log.e("Jsoup: ", "Failed to Connet");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			stories = new ArrayList<StoryEntryModel>();
			StoryEntryModel story = null;

			for (Element element : newsBody) {
				try {
					story = new StoryEntryModel(element.select("h2")
							.select("a").text().toString(), "", element
							.select("div.entry-content").select("p").first()
							.toString(), element.select("div.entry-content")
							.select("p").select("a").attr("href").toString());
					stories.add(story);
				} catch (NullPointerException ex) {
					Log.e("Jsoup: ",
							"retrieving elements from documents failed");
				}
			}

			adapter = new StoryAdapter(getActivity().getApplicationContext(),
					stories);
			mStoryList.setAdapter(adapter);
			mProgressDialog.dismiss();
		}
	}

}
